package com.sourcespro.util;

import com.sourcespro.Env;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.log.NullLogChute;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

import java.io.StringWriter;
import java.util.*;

/**
 * genCode
 *
 * @author zhanghaowei
 * @date 2018/6/16
 */
public class VelocityUtil {

    private final static VelocityEngine velocityEngine;

    static {
        velocityEngine = new VelocityEngine();
        // Disable separate Velocity logging.
        velocityEngine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, NullLogChute.class.getName());
        velocityEngine.init();
    }

    public static String evaluate(String template, Map<String, Object> map) {
        VelocityContext context = new VelocityContext();
        map.forEach(context::put);
        initVal(context);
        StringWriter writer = new StringWriter();
        velocityEngine.evaluate(context, writer, "", template);
        return writer.toString();
    }

    public static String evaluate(String template, List list, Set<String> importList) {
        VelocityContext context = new VelocityContext();
        context.put("list", list);
        context.put("importList", importList);
        initVal(context);
        StringWriter writer = new StringWriter();
        velocityEngine.evaluate(context, writer, "", template);
        return writer.toString();
    }

    private static void initVal(VelocityContext context) {
        context.put("packageName", Env.packageName);
        context.put("description", Env.description);
        context.put("author", Env.author);
        context.put("date", DateUtils.getDate());
        context.put("className", Env.className);
        context.put("tableName", Env.tableName);
        context.put("simpleIdType", Env.idType.replace("java.lang.", ""));
    }
}
